
//
//  Global.
//
var g_Callbacks = [];

//
//  Module codes.
//
console.log("[Net/Core] WebSocket is available.");

//
//  Global.
//
var g_ConnectionInstance = null;

//
//  Private APIs.
//
function WSOnOpen() {
    console.log("[Net/Core] WebSocket is opened.");
}

function WSOnMessage(msg) {
    var parsed;
    try {
        parsed = JSON.parse(msg.data);
    } catch(error) {
        console.error("[Net/Core] Received a corrupted message.");
        return;
    }
    g_Callbacks.forEach(function(callback) {
        callback.call(this, parsed);
    });
}

function WSOnError() {
    console.error("[Net/Core] Received an error.");

    //  Close the connection.
    g_ConnectionInstance.close();
}

function WSOnClose() {
    console.warn("[Net/Core] WebSocket is closed.");

    //  Reconnect.
    setTimeout(function() {
        console.log("[Net/Core] Reconnecting...");
        WSConnect();
    }, 500);
}

function WSFetchData() {
    if (g_ConnectionInstance !== null && g_ConnectionInstance.readyState == WebSocket.OPEN) {
        g_ConnectionInstance.send("fetch");
    }
}

function WSConnect() {
    //  Create the connection.
    g_ConnectionInstance = new WebSocket("ws://" + location.host + "/mq");

    //  Bind events.
    g_ConnectionInstance.onopen = WSOnOpen;
    g_ConnectionInstance.onmessage = WSOnMessage;
    g_ConnectionInstance.onerror = WSOnError;
    g_ConnectionInstance.onclose = WSOnClose;
}

//  Connect.
setTimeout(WSConnect, 0);

//  Create the fetching timer.
setInterval(WSFetchData, 125);

function cbc(dt) {
    for (var i = 0; i < dt.length; ++i) {
        var ob = dt[i];
        if (ob.device == "WARN") {
            for (var j = 1; j <= 3; ++j) {
                $(document.body).removeClass("fuck"+j);
            }
            $(document.body).addClass("fuck"+ob.value[0]);
        }
    }
}

g_Callbacks.push(cbc);
